import requests
import execjs
from lxml import etree
with open("04 main.js","r",encoding="utf-8") as f:
    js_code = f.read()
js_com=execjs.compile(js_code)

session=requests.session()

headers = {
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,ar;q=0.7",
    "cache-control": "no-cache",
    "pragma": "no-cache",
    "priority": "u=0, i",
    "referer": "https://qikan.cqvip.com/Qikan/Journal/JournalGuid?from=index",
    "sec-ch-ua": "\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Microsoft Edge\";v=\"138\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"Windows\"",
    "sec-fetch-dest": "document",
    "sec-fetch-mode": "navigate",
    "sec-fetch-site": "same-origin",
    "sec-fetch-user": "?1",
    "upgrade-insecure-requests": "1",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0"
}
url = "https://qikan.cqvip.com/Qikan/Journal/JournalGuid"
params = {
    "from": "index"
}
proxies = {
    'http': 'socks5://127.0.0.1:8442',
    'https': 'socks5://127.0.0.1:8442'
}
def fetch_1():
    response = session.get(url, headers=headers, params=params,proxies=proxies)
    with open("fetch1.html","w",encoding="utf-8") as f:
        f.write(response.text)
    print("fetch_1:::", response.status_code)
    tree = etree.HTML(response.text)
    meta_content = tree.xpath('//meta[2]/@content')[0]
    ts_js = tree.xpath('//script[1]/text()')[0]
    auto_script_url = 'https://qikan.cqvip.com' + tree.xpath('//script[@src]/@src')[0]
    auto_script_js = session.get(auto_script_url).text

    return meta_content, ts_js, auto_script_js


def generate_cookie(meta_content, ts_js, auto_script_js):
    with open("01 env.js", encoding='utf-8') as fp:
        jsCode1 = fp.read()
    jsCode1.replace("meta_content", meta_content)


    with open("ts_js.js","w",encoding="utf-8") as f:
        f.write(ts_js)
    with open("auto_script_js.js","w",encoding="utf-8") as f:
        f.write(auto_script_js)
    with open("04 main.js", encoding='utf-8') as fp:
        jsCode = fp.read()
    JS = execjs.compile(jsCode)
    js_cookie = JS.call("get_cookies")
    cookie_key_value = js_cookie.split(";")[0].split("=")
    print("ck0:::",cookie_key_value[0])
    print("ck1:::",cookie_key_value[1])
    session.cookies.update({cookie_key_value[0]: cookie_key_value[1]})
def fetch_2():
    response = session.get(url, headers=headers,params=params,proxies=proxies)
    print("fetch2:::",response.status_code)
    print("text:::",response.text)
    with open("index.html","w",encoding="utf-8") as f:
        f.write(response.text)
if __name__ == '__main__':
    meta_content, ts_js, auto_script_js=fetch_1()
    print("content:::",meta_content)

    generate_cookie(meta_content, ts_js, auto_script_js)
    fetch_2()